import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Statistic,
  Table,
  Tag,
  Progress,
  List,
  Avatar,
  Button,
  Space
} from 'antd';
import {
  ShoppingOutlined,
  TeamOutlined,
  DollarOutlined,
  EyeOutlined,
  TrophyOutlined,
  ClockCircleOutlined,
  ReloadOutlined,
  BarChartOutlined,
  UserOutlined
} from '@ant-design/icons';
import { orderAPI, productAPI, userAPI } from '../../services/api';
import { getAdminOrders, getProducts } from '../../utils/storage';
import { useAdminAuth } from '../../hooks/useAuth';

const AdminDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalUsers: 0,
    totalSales: 0,
    totalViews: 0
  });
  const [recentOrders, setRecentOrders] = useState([]);
  const [hotProducts, setHotProducts] = useState([]);
  const { user, hasAdminPermission } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadDashboardData();
  }, []);

  const loadDashboardData = async () => {
    setLoading(true);
    try {
      // 从localStorage直接获取数据以确保实时性
      const localOrders = getAdminOrders();
      const localProducts = getProducts();
      
      // 计算统计数据
      const newStats = {
        totalOrders: localOrders.length,
        totalUsers: 0, // 用户数据从API获取
        totalSales: localOrders.reduce((sum, order) => sum + (order.totalAmount || 0), 0),
        totalViews: localProducts.reduce((sum, product) => sum + (product.views || 0), 0)
      };

      // 获取最近5个订单
      const recent = localOrders.slice(0, 5);
      setRecentOrders(recent);
      
      // 获取热门商品（按销量排序）
      const sorted = [...localProducts].sort((a, b) => (b.sales || 0) - (a.sales || 0));
      setHotProducts(sorted.slice(0, 5));

      // 如果有用户查看权限，获取用户总数
      if (hasAdminPermission('user:view')) {
        try {
          const userResponse = await userAPI.getUsers({ pageSize: 1 });
          if (userResponse.success) {
            newStats.totalUsers = userResponse.data.total;
          }
        } catch (error) {
          console.error('获取用户数据失败:', error);
        }
      }

      setStats(newStats);
      
    } catch (error) {
      console.error('加载仪表板数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = () => {
    loadDashboardData();
  };

  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${amount?.toFixed(2) || '0.00'}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          pending: { color: 'orange', text: '待支付' },
          paid: { color: 'blue', text: '已支付' },
          shipped: { color: 'purple', text: '已发货' },
          delivered: { color: 'green', text: '已送达' },
          cancelled: { color: 'red', text: '已取消' }
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleDateString(),
    },
  ];

  return (
    <div>
      {/* 页面标题和操作按钮 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: 24 
      }}>
        <h2 style={{ margin: 0 }}>仪表板</h2>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
            style={buttonStyle}
          >
            刷新数据
          </Button>
          <Button 
            type="primary"
            icon={<BarChartOutlined />}
            style={buttonStyle}
          >
            详细报表
          </Button>
        </Space>
      </div>
      
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {hasAdminPermission('order:view') && (
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总订单数"
                value={stats.totalOrders}
                prefix={<ShoppingOutlined />}
                valueStyle={{ color: '#1890ff' }}
                loading={loading}
              />
              <div style={{ marginTop: 8, fontSize: '12px', color: '#999' }}>
                较昨日 +12%
              </div>
            </Card>
          </Col>
        )}
        
        {hasAdminPermission('user:view') && (
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="用户总数"
                value={stats.totalUsers}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#52c41a' }}
                loading={loading}
              />
              <div style={{ marginTop: 8, fontSize: '12px', color: '#999' }}>
                较昨日 +5%
              </div>
            </Card>
          </Col>
        )}
        
        {hasAdminPermission('order:view') && (
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总销售额"
                value={stats.totalSales}
                prefix={<DollarOutlined />}
                precision={2}
                valueStyle={{ color: '#f5222d' }}
                loading={loading}
              />
              <div style={{ marginTop: 8, fontSize: '12px', color: '#999' }}>
                较昨日 +8%
              </div>
            </Card>
          </Col>
        )}
        
        {hasAdminPermission('product:view') && (
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总浏览量"
                value={stats.totalViews}
                prefix={<EyeOutlined />}
                valueStyle={{ color: '#722ed1' }}
                loading={loading}
              />
              <div style={{ marginTop: 8, fontSize: '12px', color: '#999' }}>
                较昨日 +15%
              </div>
            </Card>
          </Col>
        )}
      </Row>

      <Row gutter={[16, 16]}>
        {/* 最近订单 */}
        {hasAdminPermission('order:view') && (
          <Col xs={24} lg={16}>
            <Card 
              title="最近订单" 
              extra={
                <Space>
                  <ClockCircleOutlined />
                  <Button 
                    type="link" 
                    size="small"
                    style={buttonStyle}
                  >
                    查看全部
                  </Button>
                </Space>
              }
            >
              <Table
                columns={orderColumns}
                dataSource={recentOrders}
                rowKey="id"
                pagination={false}
                loading={loading}
                size="small"
              />
            </Card>
          </Col>
        )}

        {/* 热门商品 */}
        {hasAdminPermission('product:view') && (
          <Col xs={24} lg={8}>
            <Card 
              title="热门商品" 
              extra={
                <Space>
                  <TrophyOutlined />
                  <Button 
                    type="link" 
                    size="small"
                    style={buttonStyle}
                  >
                    查看全部
                  </Button>
                </Space>
              }
            >
              <List
                itemLayout="horizontal"
                dataSource={hotProducts}
                loading={loading}
                renderItem={(item, index) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={
                        <Avatar 
                          size="small" 
                          style={{ 
                            backgroundColor: index < 3 ? '#1890ff' : '#999',
                            color: 'white'
                          }}
                        >
                          {index + 1}
                        </Avatar>
                      }
                      title={
                        <div style={{ fontSize: 14 }}>
                          {item.name?.length > 20 ? 
                            `${item.name.substring(0, 20)}...` : 
                            item.name
                          }
                        </div>
                      }
                      description={
                        <div>
                          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span>销量: {item.sales || 0}</span>
                            <span style={{ color: '#52c41a' }}>¥{item.price}</span>
                          </div>
                          <Progress
                            percent={Math.min(100, ((item.sales || 0) / Math.max(1, Math.max(...hotProducts.map(p => p.sales || 0)))) * 100)}
                            size="small"
                            showInfo={false}
                            strokeColor={index < 3 ? '#52c41a' : '#1890ff'}
                          />
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        )}

        {/* 欢迎信息 - 当用户没有查看权限时显示 */}
        {(!hasAdminPermission('order:view') && !hasAdminPermission('product:view')) && (
          <Col xs={24}>
            <Card>
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Avatar 
                  size={64} 
                  icon={<UserOutlined />} 
                  style={{ backgroundColor: '#1890ff', marginBottom: 16 }}
                />
                <h3>欢迎，{user?.nickname || user?.username}！</h3>
                <p style={{ color: '#666', marginBottom: 24 }}>
                  您当前的角色权限有限，请联系管理员获取更多权限。
                </p>
                <Space>
                  <Button type="primary" style={buttonStyle}>
                    申请权限
                  </Button>
                  <Button style={buttonStyle}>
                    查看帮助
                  </Button>
                </Space>
              </div>
            </Card>
          </Col>
        )}
      </Row>


    </div>
  );
};

export default AdminDashboard;